import React, { useState } from 'react'
import { MatchPlayer } from '../types/dota'

interface PlayerEconomyCurveChartProps {
  players: MatchPlayer[]
  duration: number // 比赛时长（秒）
  title: string
}

const PlayerEconomyCurveChart: React.FC<PlayerEconomyCurveChartProps> = ({ 
  players, 
  duration,
  title 
}) => {
  // 鼠标悬停状态
  const [hoveredPoint, setHoveredPoint] = useState<{
    playerIndex: number
    timeIndex: number
    x: number
    y: number
    gold: number
    playerName: string
  } | null>(null)
  if (!players || players.length === 0 || !duration) {
    return (
      <div className="w-full h-96 flex items-center justify-center bg-muted/20 rounded-lg">
        <p className="text-muted-foreground">暂无数据</p>
      </div>
    )
  }

  // 图表尺寸
  const width = 800
  const height = 400
  const margin = { top: 20, right: 120, bottom: 40, left: 60 }
  const chartWidth = width - margin.left - margin.right
  const chartHeight = height - margin.top - margin.bottom

  // 计算时间点（每分钟一个点）
  const durationMinutes = Math.ceil(duration / 60)
  const timePoints = Array.from({ length: durationMinutes + 1 }, (_, i) => i)

  // 为每个玩家生成经济曲线数据
  const generatePlayerCurve = (player: MatchPlayer) => {
    const gpm = player.gold_per_min
    const finalGold = player.total_gold || gpm * durationMinutes
    
    // 模拟经济增长曲线（考虑早期较慢，中后期加速的特点）
    return timePoints.map(minute => {
      if (minute === 0) return 625 // 初始金钱
      
      // 使用二次函数模拟经济增长，早期慢，后期快
      const progress = minute / durationMinutes
      const baseGold = 625 + (gpm * minute)
      
      // 添加一些随机波动和非线性增长
      const growthFactor = 0.8 + 0.4 * Math.pow(progress, 1.2)
      const randomFactor = 0.95 + 0.1 * Math.sin(minute * 0.5) // 小幅波动
      
      return Math.max(625, baseGold * growthFactor * randomFactor)
    })
  }

  // 生成所有玩家的曲线数据
  const playerCurves = players.map(player => ({
    player,
    data: generatePlayerCurve(player),
    isRadiant: player.player_slot < 128
  }))

  // 计算Y轴范围
  const allValues = playerCurves.flatMap(curve => curve.data)
  const maxGold = Math.max(...allValues)
  const minGold = Math.min(...allValues)
  const goldRange = maxGold - minGold

  // 坐标转换函数
  const xScale = (minute: number) => (minute / durationMinutes) * chartWidth
  const yScale = (gold: number) => chartHeight - ((gold - minGold) / goldRange) * chartHeight

  // 颜色配置 - 为20个玩家提供不同的颜色
  const playerColors = [
    '#22c55e', '#16a34a', '#15803d', '#166534', '#14532d', // 天辉绿色系
    '#ef4444', '#dc2626', '#b91c1c', '#991b1b', '#7f1d1d', // 夜魇红色系
    '#3b82f6', '#2563eb', '#1d4ed8', '#1e40af', '#1e3a8a', // 蓝色系
    '#f59e0b', '#d97706', '#b45309', '#92400e', '#78350f'  // 橙色系
  ]

  const getPlayerColor = (playerIndex: number) => {
    return playerColors[playerIndex % playerColors.length]
  }

  // 生成路径字符串
  const generatePath = (data: number[]) => {
    return data.map((gold, index) => {
      const x = xScale(index)
      const y = yScale(gold)
      return index === 0 ? `M ${x} ${y}` : `L ${x} ${y}`
    }).join(' ')
  }

  // 格式化金钱显示
  const formatGold = (gold: number) => {
    if (gold >= 1000) {
      return `${(gold / 1000).toFixed(1)}k`
    }
    return Math.round(gold).toString()
  }

  return (
    <div className="w-full">
      <h3 className="text-lg font-semibold mb-4">{title}</h3>
      <div className="bg-card rounded-lg p-4 border">
        <svg width={width} height={height} className="overflow-visible">
          {/* 背景网格 */}
          <defs>
            <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
              <path d="M 40 0 L 0 0 0 40" fill="none" stroke="currentColor" strokeWidth="0.5" opacity="0.1"/>
            </pattern>
          </defs>
          <rect 
            x={margin.left} 
            y={margin.top} 
            width={chartWidth} 
            height={chartHeight} 
            fill="url(#grid)" 
          />

          {/* Y轴刻度线和标签 */}
          {Array.from({ length: 6 }, (_, i) => {
            const value = minGold + (goldRange * i / 5)
            const y = margin.top + yScale(value)
            return (
              <g key={i}>
                <line
                  x1={margin.left}
                  y1={y}
                  x2={margin.left + chartWidth}
                  y2={y}
                  stroke="currentColor"
                  strokeWidth="0.5"
                  opacity="0.2"
                />
                <text
                  x={margin.left - 10}
                  y={y + 4}
                  textAnchor="end"
                  fontSize="12"
                  fill="currentColor"
                  opacity="0.7"
                >
                  {formatGold(value)}
                </text>
              </g>
            )
          })}

          {/* X轴刻度线和标签 */}
          {Array.from({ length: Math.min(11, durationMinutes + 1) }, (_, i) => {
            const minute = Math.floor((durationMinutes * i) / 10)
            const x = margin.left + xScale(minute)
            return (
              <g key={i}>
                <line
                  x1={x}
                  y1={margin.top}
                  x2={x}
                  y2={margin.top + chartHeight}
                  stroke="currentColor"
                  strokeWidth="0.5"
                  opacity="0.2"
                />
                <text
                  x={x}
                  y={margin.top + chartHeight + 20}
                  textAnchor="middle"
                  fontSize="12"
                  fill="currentColor"
                  opacity="0.7"
                >
                  {minute}分
                </text>
              </g>
            )
          })}

          {/* 绘制玩家曲线 */}
          <g transform={`translate(${margin.left}, ${margin.top})`}>
            {playerCurves.map((curve, playerIndex) => (
              <g key={curve.player.account_id || playerIndex}>
                {/* 曲线路径 */}
                <path
                  d={generatePath(curve.data)}
                  fill="none"
                  stroke={getPlayerColor(playerIndex)}
                  strokeWidth="2"
                  opacity="0.8"
                />
                {/* 数据点 - 用于鼠标交互 */}
                {curve.data.map((gold, timeIndex) => (
                  <circle
                    key={timeIndex}
                    cx={xScale(timeIndex)}
                    cy={yScale(gold)}
                    r="4"
                    fill={getPlayerColor(playerIndex)}
                    opacity="0"
                    style={{ cursor: 'pointer' }}
                    onMouseEnter={(e) => {
                      const rect = e.currentTarget.getBoundingClientRect()
                      setHoveredPoint({
                        playerIndex,
                        timeIndex,
                        x: rect.left + rect.width / 2,
                        y: rect.top,
                        gold,
                        playerName: curve.player.personaname || `玩家${playerIndex + 1}`
                      })
                    }}
                    onMouseLeave={() => setHoveredPoint(null)}
                  />
                ))}
              </g>
            ))}
          </g>

          {/* 轴标签 */}
          <text
            x={margin.left + chartWidth / 2}
            y={height - 5}
            textAnchor="middle"
            fontSize="14"
            fill="currentColor"
            opacity="0.8"
          >
            时间 (分钟)
          </text>
          <text
            x={15}
            y={margin.top + chartHeight / 2}
            textAnchor="middle"
            fontSize="14"
            fill="currentColor"
            opacity="0.8"
            transform={`rotate(-90, 15, ${margin.top + chartHeight / 2})`}
          >
            净值 (金钱)
          </text>
        </svg>

        {/* 悬停提示框 */}
        {hoveredPoint && (
          <div
            className="fixed z-50 bg-popover border rounded-lg shadow-lg p-3 pointer-events-none"
            style={{
              left: hoveredPoint.x - 60,
              top: hoveredPoint.y - 80,
            }}
          >
            <div className="text-sm font-semibold">{hoveredPoint.playerName}</div>
            <div className="text-xs text-muted-foreground">
              时间: {hoveredPoint.timeIndex}分钟
            </div>
            <div className="text-xs text-muted-foreground">
              净值: {formatGold(hoveredPoint.gold)}
            </div>
          </div>
        )}

        {/* 图例 */}
        <div className="mt-4 grid grid-cols-2 gap-2 text-sm">
          <div>
            <h4 className="font-semibold text-green-600 mb-2">天辉 (Radiant)</h4>
            {playerCurves
              .filter(curve => curve.isRadiant)
              .map((curve, index) => {
                const playerIndex = players.indexOf(curve.player)
                return (
                  <div key={curve.player.account_id || index} className="flex items-center space-x-2 mb-1">
                    <div 
                      className="w-3 h-0.5 rounded"
                      style={{ backgroundColor: getPlayerColor(playerIndex) }}
                    />
                    <span className="text-xs">
                      {curve.player.personaname || `玩家${playerIndex + 1}`} 
                      ({formatGold(curve.data[curve.data.length - 1])})
                    </span>
                  </div>
                )
              })}
          </div>
          <div>
            <h4 className="font-semibold text-red-600 mb-2">夜魇 (Dire)</h4>
            {playerCurves
              .filter(curve => !curve.isRadiant)
              .map((curve, index) => {
                const playerIndex = players.indexOf(curve.player)
                return (
                  <div key={curve.player.account_id || index} className="flex items-center space-x-2 mb-1">
                    <div 
                      className="w-3 h-0.5 rounded"
                      style={{ backgroundColor: getPlayerColor(playerIndex) }}
                    />
                    <span className="text-xs">
                      {curve.player.personaname || `玩家${playerIndex + 1}`} 
                      ({formatGold(curve.data[curve.data.length - 1])})
                    </span>
                  </div>
                )
              })}
          </div>
        </div>
      </div>
    </div>
  )
}

export default PlayerEconomyCurveChart